﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ProxyHero.Entity;
using ProxyHero.Common;
using System.IO;

namespace ProxyHero.Setting
{
    public partial class frmOption : Form
    {
        #region Constructors
        public frmOption()
        {
            InitializeComponent();
        }
        #endregion

        #region Operation
        private void frmOption_Load(object sender, EventArgs e)
        {
            try
            {
                InitTestSetting();
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
                MsgBox.ShowMessage("应用成功！");
            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Save();
            this.Close();
        }

        private void cbbChoose_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //在选择帐号时并配置帐号相关信息显示到控件

                if (this.cbbChoose.SelectedItem == null)
                {
                    return;
                }

                TestEntity testSetting = this.cbbChoose.SelectedItem as TestEntity;
                if (testSetting == null)
                {
                    return;
                }

                this.txtUrl.Text = testSetting.TestUrl;
                this.txtTitle.Text = testSetting.TestWebTitle;
                this.txtEncoding.Text = testSetting.TestWebEncoding;

            }
            catch (Exception ex)
            {
                MsgBox.ShowExceptionMessage(ex);
            }
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder("【操作系统版本】: ");
            sb.Append(OSVersion.VersionString);
            sb.Append("\n【PH主程序版本】: ");
            sb.Append(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
            sb.Append("\n【IE浏览器版本】: ");
            sb.Append(OSVersion.InternetExplorerVersion);
            sb.Append("\n【软件安装目录】: ");
            sb.Append(Application.StartupPath);
            this.rtbSystemInfo.Text = sb.ToString();
        }

        #endregion

        #region Methods

        private void Save()
        {
            TestEntity te = new TestEntity();

            #region 设置验证选项
            if (!this.txtEncoding.Text.Trim().Equals("") &&
                !this.txtTitle.Text.Trim().Equals("") &&
                    !this.txtUrl.Text.Trim().Equals(""))
            {
                te.TestUrl = this.txtUrl.Text.Trim();
                te.TestWebTitle = this.txtTitle.Text.Trim();
                te.TestWebEncoding = this.txtEncoding.Text.Trim();
            }
            #endregion

            #region 系统选项
            SetStartPage();
            #endregion

            SaveLoginSetting(te);
        }

        /// <summary>
        /// 加载登录信息
        /// </summary>
        private void InitTestSetting()
        {
            this.cbbChoose.DisplayMember = "TestUrl";
            this.cbbChoose.ValueMember = "TestUrl";
            ConfigEntity _localConfig = Config.LocalConfig;

            //如果存在登录信息文件则读取信息

            if (_localConfig == null)
            {
                _localConfig = new ConfigEntity();
            }

            for (int i = 0; i < _localConfig.TestSetting.Count; i++)
            {
                TestEntity temp = _localConfig.TestSetting[i];
                if (!this.cbbChoose.Items.Contains(temp))
                {
                    this.cbbChoose.Items.Add(temp);
                }
            }

            this.cbCooperation.Checked = Config.LocalConfig.IsCooperation && ProxyHelper.GetStartPage(Config.IEStartPage);
            if (this.cbCooperation.Checked)
            {
                this.nudChangeProxyInterval.Minimum = 2;
            }
            else
            {
                this.nudChangeProxyInterval.Minimum = 5;
            }
            this.nudTestOutTime.Value = _localConfig.TestTimeOut;
            this.nudChangeProxyInterval.Value = _localConfig.AutoChangeProxyInterval < this.nudChangeProxyInterval.Minimum ? this.nudChangeProxyInterval.Minimum : Config._localConfig.AutoChangeProxyInterval;
            this.nudThreadsCount.Value = _localConfig.TestThreadsCount;
            this.nupAutoProxySpeed.Value = _localConfig.AutoProxySpeed;
            this.cbbDefaultStartPage.Text = _localConfig.DefaultStartPage;
            this.cbCheckAnonymous.Checked = _localConfig.CheckAnonymous;
            this.cbbDefaultStartPage.Text = _localConfig.DefaultStartPage;

            if (this.cbbChoose.Items.Count > 0)
            {
                if (Config._localConfig != null && _localConfig.DefaultTestUrl != null)
                {
                    for (int i = 0; i < this.cbbChoose.Items.Count; i++)
                    {
                        TestEntity te = this.cbbChoose.Items[i] as TestEntity;
                        if (te.TestUrl.ToLower() == _localConfig.DefaultTestUrl.TestUrl.ToLower())
                        {
                            this.cbbChoose.SelectedIndex = i;
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        /// <param name="loginSetting"></param>
        private void SaveLoginSetting(TestEntity testSetting)
        {
            TestEntity searchSetting = this.FindLoginSettingByAccount(testSetting.TestUrl);

            Config._localConfig.DefaultTestUrl = testSetting;
            Config._localConfig.IsCooperation = this.cbCooperation.Checked;
            Config._localConfig.AutoChangeProxyInterval = (int)this.nudChangeProxyInterval.Value;
            Config._localConfig.TestTimeOut = (int)this.nudTestOutTime.Value;
            Config._localConfig.TestThreadsCount = (int)this.nudThreadsCount.Value;
            Config._localConfig.AutoProxySpeed = (int)this.nupAutoProxySpeed.Value;
            Config._localConfig.DefaultStartPage = this.cbbDefaultStartPage.Text;
            Config._localConfig.CheckAnonymous = this.cbCheckAnonymous.Checked;

            if (Config._localConfig.AutoChangeProxyInterval != Config._localConfig.AutoChangeProxyInterval)
            {
                if (Config.MainForm.timerAutoChangeProxy.Enabled)
                {
                    Config.ProxyViewForm.StopAutoChange();
                    Config.MainForm.tsslCountdown.Text = DateTime.Now.ToShortDateString();
                }
            }
            if (Config._localConfig.AutoProxySpeed != Config._localConfig.AutoProxySpeed)
            {
                if (Config.MainForm.timerAutoChangeProxy.Enabled)
                {
                    Config.ProxyViewForm.StopAutoChange();
                    Config.MainForm.tsslCountdown.Text = DateTime.Now.ToShortDateString();
                }
            }

            if (searchSetting != null && searchSetting.TestUrl != "")
            {
                if (searchSetting.TestUrl == testSetting.TestUrl) //如果已经设置，则移除换成新的
                {
                    Config._localConfig.TestSetting.Remove(searchSetting);
                    Config._localConfig.DefaultTestUrl = testSetting;
                }
            }

            if (!this.Contains(testSetting))
            {
                Config._localConfig.TestSetting.Add(testSetting);
            }
     
            bool res = XmlHelper.XmlSerialize(Config.ConfigPath, Config._localConfig, typeof(ConfigEntity));
            if (!res)
            {
                MsgBox.ShowErrorMessage("保存失败！");
            }
        }

        private bool Contains(TestEntity testEntity)
        {
            bool result = false;
            foreach (TestEntity te in Config._localConfig.TestSetting)
            {
                if (te.TestUrl.ToLower() == testEntity.TestUrl.ToLower())
                {
                    result = true;
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// 通过帐号获取登录配置信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public TestEntity FindLoginSettingByAccount(string testUrl)
        {
            foreach (TestEntity temp in Config._localConfig.TestSetting)
            {
                if (temp.TestUrl == testUrl)
                {
                    return temp;
                }
            }
            return null;
        }

        private void SetStartPage()
        {
            string[] res;
            if (this.cbCooperation.Checked)
            {
                res = ProxyHelper.SetStartPage(Config.IEStartPage, true);
                if (Config.MainForm != null && ProxyHelper.GetStartPage(Config.IEStartPage))
                {
                    Config.MainForm.Text = Application.ProductName + "合作版 v" + Application.ProductVersion;
                }
            }
            else
            {
                res = ProxyHelper.SetStartPage(Config.IEStartPage, false);
                if (Config.MainForm != null)
                {
                    Config.MainForm.Text = Application.ProductName + "个人版 v" + Application.ProductVersion;
                }
            }

            if (res[1] != "")
            {
                MsgBox.ShowMessage(res[1]);
            }
        }
        #endregion
    }
}
